﻿using LdtJudge.DataEngine.CallInterface.CommHelp;
using LdtJudge.DataEngine.Model.DataModel.CommonManageModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace LdtJudge.DataEngine.Data
{
    /// <summary>
    /// 该类定位操作规则库数据业务
    /// </summary>
    public class SqlCmmCommon : SqlComDataHandle
    {
        //private static string conncmm = "LdtCommonManage";

        //public  SqlHandle sqhandle;

        private static IFreeSql freeSql = FreeSQLHelp.GetFreeSQL("LdtCommonManage");

        /// <summary>
        /// 缓存数据
        /// </summary>
        public Dictionary<string, object> DicTabel = new Dictionary<string, object>();
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connectionstring"></param>

        public SqlCmmCommon(string key)
        {
            freeSql = FreeSQLHelp.GetFreeSQL(key);
        }

        /// <summary>
        /// 根据段落编号及段落编号所属模块进行配置
        /// </summary>
        /// <param name="paragracode">段落编号</param>
        /// <param name="modulecode">模块编号</param>
        /// <returns></returns>
        public List<ExtractInfo> GetExtractInfoByParagraCode(string paragraCode, string moduleCode)
        {
            
            if (DicTabel.ContainsKey("ExtractInfo"))
            {
                List<ExtractInfo> tableList = (List<ExtractInfo>)DicTabel["ExtractInfo"];
                List<ExtractInfo> table = tableList.Where(a => a.EXIParagraCode.ToLower() == paragraCode.ToLower())?.ToList() ;
                return table;
            }
            else
            {
                var table = freeSql.Select<ExtractInfo>().Where(a => a.EXIParagraCode == paragraCode);
                if (table.Count() > 0)
                {
                    return table.ToList();
                }
            }
            
            return null;
        }
        /// <summary>
        /// 根据xmlpath及段落编号所属模块进行配置
        /// </summary>
        /// <param name="xmlpath">段落编号</param>
        /// <param name="modulecode">模块编号</param>
        /// <returns></returns>
        public List<ExtractInfo> GetExtractInfoByXmlPath(string xmlPath, string moduleCode)
        {
            if (DicTabel.ContainsKey("ExtractInfo"))
            {
                List<ExtractInfo> tableList = (List<ExtractInfo>)DicTabel["ExtractInfo"];
                List<ExtractInfo> table = tableList.Where(a => a.EXIXmlPath == xmlPath)?.ToList();
                return table;
            }
            else
            {
                var table = freeSql.Select<ExtractInfo>().Where(a => a.EXIXmlPath == xmlPath);
                if (table.Count() > 0)
                {
                    string f = freeSql.Select<ExtractInfo>().Where(a => a.EXIXmlPath == xmlPath).ToSql();
                    return table.ToList();
                }
            }

               
            return null;
        }

        /// <summary>
        /// 根据Exi_ID进行查询特征信息表的数据信息
        /// </summary>
        /// <param name="exi_idList">主键ID集合</param>
        /// <returns></returns>
        public List<ExtractFeature> GetExtractFeatureInfoByExiIdList(List<string> exi_idList)
        {
            string sqlstr = $"SELECT * FROM dbo.ExtractFeature WHERE EXI_ID in ('{string.Join("','", exi_idList) }')";

            if (DicTabel.ContainsKey("ExtractFeature"))
            {
                List<ExtractFeature> tableList = (List<ExtractFeature>)DicTabel["ExtractFeature"];
                List<ExtractFeature> table = tableList.Where(a => exi_idList.Contains(a.EXIID))?.ToList();
                return table;
            }
            else
            {
                var table = freeSql.Select<ExtractFeature>().Where(a => exi_idList.Contains(a.EXIID));
                if (table.Count() > 0)
                {
                    return table.ToList();
                }
            }
            return null;
        }

        /// <summary>
        /// 通用的数据查询方法
        /// </summary>
        /// <param name="tablename">表名称</param>
        /// <param name="pkid">主键ID</param>
        /// <param name="pkvalue">主键值</param>
        /// <returns></returns>
        public DataTable GetCommonTableData(string tablename, string pkid, string pkvalue)
        {
            //return sqhandle.GetTableData(tablename, pkid, pkvalue);
            DataTable dataTable = new DataTable();
            if (tablename.ToLower()== "elementextractsource")
            {
                if (DicTabel.ContainsKey("ElementExtractSource"))
                {
                    List<ElementExtractSource> tableList = (List<ElementExtractSource>)DicTabel["ElementExtractSource"];
                    dataTable= FillDataTable<ElementExtractSource>(tableList.Where(a => a.EES_ID == pkvalue)?.ToList());
                }
                else
                {
                    List<ElementExtractSource> elementExtractSourcesList = freeSql.Select<ElementExtractSource>().Where(a => a.EES_ID == pkvalue)?.ToList();
                    dataTable = FillDataTable<ElementExtractSource>(elementExtractSourcesList);
                }
                
            }
            else if (tablename.ToLower() == "ruleinfounit")
            {
                if (DicTabel.ContainsKey("ruleinfounit"))
                {
                    List<RuleInfoUnit> tableList = (List<RuleInfoUnit>)DicTabel["ruleinfounit"];
                    dataTable = FillDataTable<RuleInfoUnit>(tableList.Where(a => a.RIU_ID == pkvalue)?.ToList());
                }
                else
                {
                    List<RuleInfoUnit> elementExtractSourcesList = freeSql.Select<RuleInfoUnit>().Where(a => a.RIU_ID == pkvalue)?.ToList();
                    dataTable = FillDataTable<RuleInfoUnit>(elementExtractSourcesList);
                }
                
            }
            else if (tablename.ToLower() == "returnmode")
            {
                if (DicTabel.ContainsKey("returnmode"))
                {
                    List<ReturnMode> tableList = (List<ReturnMode>)DicTabel["returnmode"];
                    dataTable = FillDataTable<ReturnMode>(tableList.Where(a => a.RM_ID == pkvalue)?.ToList());
                }
                else
                {
                    List<ReturnMode> elementExtractSourcesList = freeSql.Select<ReturnMode>().Where(a => a.RM_ID == pkvalue)?.ToList();
                    dataTable = FillDataTable<ReturnMode>(elementExtractSourcesList);
                }
                
            }
            else if (tablename.ToLower()== "convertmode")
            {
                if (DicTabel.ContainsKey("convertmode"))
                {
                    List<ConvertMode> tableList = (List<ConvertMode>)DicTabel["convertmode"];
                    dataTable = FillDataTable<ConvertMode>(tableList.Where(a => a.CM_ID == pkvalue)?.ToList());
                }
                else
                {
                    List<ConvertMode> elementExtractSourcesList = freeSql.Select<ConvertMode>().Where(a => a.CM_ID == pkvalue)?.ToList();

                    dataTable = FillDataTable<ConvertMode>(elementExtractSourcesList);
                }
                   
            }
            return dataTable;
        }

        /// <summary>
        /// 实体类转换成DataTable
        /// 调用示例：DataTable dt= FillDataTable(Entitylist.ToList());
        /// </summary>
        /// <param name="modelList">实体类列表</param>
        /// <returns></returns>
        public DataTable FillDataTable<T>(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
            DataTable dt = CreateData(modelList[0]);//创建表结构

            foreach (T model in modelList)
            {
                DataRow dataRow = dt.NewRow();
                foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
                {
                    if (propertyInfo.GetValue(model, null)!=null)
                    {
                        dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
                    }
                }
                dt.Rows.Add(dataRow);
            }
            return dt;
        }

        /// <summary>
        /// 根据实体类得到表结构
        /// </summary>
        /// <param name="model">实体类</param>
        /// <returns></returns>
        private DataTable CreateData<T>(T model)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);
            foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
            {
                if (propertyInfo.PropertyType.Name == "Nullable`1")
                {
                    Type columnType = propertyInfo.PropertyType;
                    columnType = columnType.GetGenericArguments()[0];
                    dataTable.Columns.Add(new DataColumn(propertyInfo.Name).ToString(), columnType);// Type.GetType("System.String")) ;
                }
                else
                {
                    dataTable.Columns.Add(new DataColumn(propertyInfo.Name).ToString(), propertyInfo.PropertyType);// Type.GetType("System.String")) ;
                }
            }
            return dataTable;
        }


        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        //public DataTable GetCommonData(string sql)
        //{
        //    return sqhandle.GetSqlHelper.ExecuteReader(sql);
        //}

        ///// <summary>
        ///// 添加数据
        ///// </summary>
        ///// <param name="sql">添加语句</param>
        ///// <returns></returns>
        //public bool AddCommonData(string sql)
        //{

        //    int re = 0;
        //    try
        //    {
        //        re = sqhandle.GetSqlHelper.ExecuteNonQuery(sql);
        //    }
        //    catch (Exception ex)
        //    {
        //        string message = ex.Message;
        //    }
        //    return (re > 0) ? true : false;

        //}

        /// <summary>
        /// 根据Exi_ID进行查询特征信息表的数据信息
        /// </summary>
        /// <param name="exi_id">主键ID</param>
        /// <returns></returns>
        //public DataTable GetExtractFeatureInfoByExiId(string exi_id)
        //{
        //    string sqlstr = $"SELECT * FROM dbo.ExtractFeature WHERE EXI_ID='{exi_id}'";
        //    return sqhandle.GetSqlHelper.ExecuteReader(sqlstr);
        //}

        ///// <summary>
        ///// 根据主键信息进行获取ElementExtractSource表的配置数据
        ///// </summary>
        ///// <param name="ess_id">主键ID</param>
        ///// <returns></returns>
        //public DataTable GetElementExtractSourceByID(string ess_id)
        //{
        //   return sqhandle.GetTableData("ElementExtractSource", "EES_ID", ess_id);
        //}

        /// <summary>
        /// 根据主键信息进行获取ConvertMode表的配置数据
        /// </summary>
        /// <param name="cm_id">主键ID</param>
        /// <returns></returns>
        //public DataTable GetConvertModeByID(string cm_id)
        //{
        //    return sqhandle.GetTableData("ConvertMode", "CM_ID", cm_id);
        //}

        /// <summary>
        /// 根据主键信息进行获取ReturnMode表的配置数据
        /// </summary>
        /// <param name="rm_id">主键ID</param>
        /// <returns></returns>
        //public DataTable GetReturnModeByID(string rm_id)
        //{
        //    return sqhandle.GetTableData("ReturnMode", "RM_ID", rm_id);
        //}

        /// <summary>
        /// 根据RiuCode获取对应的RiuID
        /// </summary>
        /// <param name="riuCode">RiuCode</param>
        /// <returns></returns>
        public List<RuleInfoUnit> GetRiuIDbyRiuCode(string riuCode)
        {
            string sqlstr = $"SELECT RIU_ID FROM dbo.RuleInfoUnit WHERE RIU_Code = '" + riuCode + "'  ORDER BY RIU_ID desc";

            List<RuleInfoUnit> ruleInfoUnitList= freeSql.Select<RuleInfoUnit>().Where(a => a.RIU_Code == riuCode).OrderBy(a => a.RIU_ID).ToList();
            return ruleInfoUnitList;
        }
        /// <summary>
        /// 根据coed获取正则内容
        /// </summary>
        /// <param name="riuCode">正则编号</param>
        /// <returns></returns>
        public List<string> GetRiuCodebyReg(string riuCode)
        {
            List<string> strlist= freeSql.Select<RuleInfoUnit, RiuRuleRelation, RiuRegexs>().LeftJoin((a, b, c) => a.RIU_ID == b.RIUID).LeftJoin((a, b, c) => b.RRRelationTableID == c.ERID).
                Where((a, b, c) => a.RIU_Code == riuCode )?.ToList((a, b, c) => c.ERRegexText);

            return strlist;
        }

        /// <summary>
        /// 通过节点路径和模块名称获取转换函数数据
        /// </summary>
        /// <param name="nodePath">节点路径</param>
        /// <param name="moduleName">模块名称</param>
        /// <returns></returns>
        public ConvertMode GetConvertModeForML(string nodePath,string moduleName)
        {
            ConvertMode model = null;
            if (!string.IsNullOrWhiteSpace(moduleName))
                moduleName = moduleName.ToLower();
            if (DicTabel.ContainsKey("ExtractFeature") && DicTabel.ContainsKey("ExtractInfo") && DicTabel.ContainsKey("ConvertMode"))
            {
                List<ExtractFeature> featureList = (List<ExtractFeature>)DicTabel["ExtractFeature"];
                List<ExtractInfo> ectractList = (List<ExtractInfo>)DicTabel["ExtractInfo"];
                List<ConvertMode> convertModeList = (List<ConvertMode>)DicTabel["ConvertMode"];
                model = (from extract in ectractList
                         join feature in featureList
                         on extract.EXIID equals feature.EXIID
                         join convert in convertModeList
                         on feature.CMID equals convert.CM_ID
                         where extract.EXIXmlPath == nodePath
                         where feature.EFModuleCode.ToLower() == moduleName
                         select convert).FirstOrDefault();
            }
            else
            {
                model = freeSql.Select<ExtractInfo, ExtractFeature, ConvertMode>()
                             .InnerJoin((a, b, c) => a.EXIID == b.EXIID)
                             .InnerJoin((a, b, c) => b.CMID == c.CM_ID)
                             .Where((a, b, c) => a.EXIXmlPath == nodePath)
                             .Where((a, b, c) => b.EFModuleCode.ToLower() == moduleName)
                             .ToOne((a, b, c) => c);
            }
            return model;
        }

    }
}
